package com.example.takephotovideo.activity;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import com.example.takephotovideo.R;
import com.example.takephotovideo.adapter.RecyclerviewTakePhotoAdapter;
import com.example.takephotovideo.base.BaseActivity;
import com.example.takephotovideo.customview.headview.HeadCustomView;
import com.example.takephotovideo.takephotovideo.PhotoVideoListBean;
import com.example.takephotovideo.takephotovideo.RvListBean;
import com.example.takephotovideo.utils.FileUtil;
import com.example.takephotovideo.utils.MyGlideEngine;
import com.example.takephotovideo.utils.PathUtils;
import com.example.takephotovideo.utils.UUIDUtils;
import com.google.gson.Gson;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class RecyclerviewActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    private HeadCustomView title;
    private RecyclerView recyclerview;
    private int REQUEST_CODE_CHOOSE = 10086;
    private static final int PRC_PHOTO_PREVIEW = 10010;
    private RecyclerviewTakePhotoAdapter adapter;
    private List<RvListBean.ResultDataBean> rvListBeanList = new ArrayList<>();
    private int surplus;
    String[] perms = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };
    private int TakePhotoIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recyclerview);
        title = (HeadCustomView) findViewById(R.id.title);
        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        title.setTextTitle("测试选择在recyclerview中的使用");
        Gson gson = new Gson();

        RvListBean rvListBean = gson.fromJson(json, RvListBean.class);
        for (int i = 0; i < rvListBean.getResultData().size(); i++) {
            if (rvListBean.getResultData().get(i).getType() == 3) {
                List<RvListBean.ResultDataBean.PhotoVideoListBean> photoVideoListBeanList = new ArrayList<>();
                List<String> result = Arrays.asList(rvListBean.getResultData().get(i).getValue().split(","));
                for (int k = 0; k < result.size(); k++) {
                    if (!result.get(k).equals("")) {
                        photoVideoListBeanList.add(new RvListBean.ResultDataBean.PhotoVideoListBean(result.get(k), false, UUIDUtils.getRandomNumNumber()));
                    }
                }
                rvListBean.getResultData().get(i).setPhotoVideoListBeanList(photoVideoListBeanList);
            }
        }
        rvListBeanList.addAll(rvListBean.getResultData());
        adapter = new RecyclerviewTakePhotoAdapter(this, rvListBeanList);
        adapter.setOnItemClickListener(new RecyclerviewTakePhotoAdapter.OnItemClickListener() {
            @Override
            public void addPhotoVideo(int surplusNumber, int position) {
                surplus = surplusNumber;
                TakePhotoIndex = position;
                methodRequiresTwoPermission();
            }
        });
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        recyclerview.setAdapter(adapter);
    }

    //请求码
    @AfterPermissionGranted(PRC_PHOTO_PREVIEW)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(this, perms)) {
            /**
             *  选择视频和图片
             *  .choose(MimeType.ofAll())
             *  选择图片
             *  .choose(MimeType.ofImage())
             *  选择视频
             *  .choose(MimeType.ofVideo())
             *  自定义选择选择的类型
             *  .choose(MimeType.of(MimeType.JPEG, MimeType.PNG, MimeType.MP4))
             */
            Matisse.from(RecyclerviewActivity.this)
                    //选择视频和图片
//                    .choose(MimeType.ofAll(), false)
                    .choose(MimeType.ofImage(), false)

                    //有序选择图片 123456...
                    .countable(true)
                    //最大选择数量为9
                    .maxSelectable(surplus)
                    //是否只显示选择的类型的缩略图，就不会把所有图片视频都放在一起，而是需要什么展示什么
                    .showSingleMediaType(true)
                    //选择方向
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    //这两行要连用 是否在选择图片中展示照相 和适配安卓7.0 FileProvider
                    .capture(true)
                    .captureStrategy(new CaptureStrategy(true, "PhotoPicker"))
                    //蓝色主题
                    .theme(R.style.Matisse_Zhihu)
                    //黑色主题
//                    .theme(R.style.Matisse_Dracula)
                    //界面中缩略图的质量
                    .thumbnailScale(0.85f)
                    //Glide加载方式
                    .imageEngine(new MyGlideEngine())
                    .forResult(REQUEST_CODE_CHOOSE);
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "选择图片需要以下权限:", PRC_PHOTO_PREVIEW, perms);
        }
    }

    /**
     * 拒绝权限前往设置中开启权限的回调
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            methodRequiresTwoPermission();
        } else if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            List<PhotoVideoListBean> fileListBeans = new ArrayList<>();
            for (int i = 0; i < mSelected.size(); i++) {
                try {
                    if ("mp4".equals(FileUtil.getFileType(PathUtils.getPath(this, mSelected.get(i))
                    ))) {
                        fileListBeans.add(new PhotoVideoListBean(PathUtils.getPath(this, mSelected.get(i)), true, UUIDUtils.getRandomNumNumber()));
                    } else {
                        fileListBeans.add(new PhotoVideoListBean(PathUtils.getPath(this, mSelected.get(i)), false, UUIDUtils.getRandomNumNumber()));
                    }
                } catch (Exception e) {
                }
            }
            List<RvListBean.ResultDataBean.PhotoVideoListBean> photoVideoListBeanList = new ArrayList<>();
            for (int i = 0; i < fileListBeans.size(); i++) {
                photoVideoListBeanList.add(new Gson().fromJson(new Gson().toJson(fileListBeans.get(i)), RvListBean.ResultDataBean.PhotoVideoListBean.class));
            }
            rvListBeanList.get(TakePhotoIndex).setPhotoVideoListBeanList(photoVideoListBeanList);
            adapter.notifyItemChanged(TakePhotoIndex, 3);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // EasyPermissions 权限处理请求结果
        Log.i("DDD", "onRequestPermissionsResult:" + requestCode);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //同意授权
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Log.d("DDD", "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    //拒绝授权
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Log.d("DDD", "onPermissionsDenied:" + requestCode + ":" + perms.size());
        new AppSettingsDialog.Builder(this)
                .setTitle("提醒")
                .setRationale("此app需要这些权限才能正常使用")
                .build()
                .show();
    }


    public String json = "{\n" +
            "    \"result\": \"200\",\n" +
            "    \"errorCode\": null,\n" +
            "    \"errorMsg\": \"获取成功\",\n" +
            "    \"resultData\": [\n" +
            "        {\n" +
            "            \"id\": 31,\n" +
            "            \"name\": \"到访图片\",\n" +
            "            \"type\": 3,\n" +
            "            \"keydowntype\": 1,\n" +
            "            \"isbitian\": 1,\n" +
            "            \"morenlist\": null,\n" +
            "            \"value\": \"http://47.100.250.181:8080/images/37WKKVZF.jpg,http://47.100.250.181:8080/images/37WKKVZF.jpg\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"id\": 48,\n" +
            "            \"name\": \"图片\",\n" +
            "            \"type\": 3,\n" +
            "            \"keydowntype\": 1,\n" +
            "            \"isbitian\": 0,\n" +
            "            \"morenlist\": null,\n" +
            "            \"value\": \"\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"id\": 49,\n" +
            "            \"name\": \"图片\",\n" +
            "            \"type\": 3,\n" +
            "            \"keydowntype\": 1,\n" +
            "            \"isbitian\": 0,\n" +
            "            \"morenlist\": null,\n" +
            "            \"value\": \"\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
}
